package com.rongke.web.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.BankCard.CheckBankCard;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.model.*;
import com.rongke.redis.RedisClusterCache;
import com.rongke.service.*;
import com.rongke.sms.SmsService;
import com.rongke.utils.*;
import com.rongke.web.yiyuan.util.XmlUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Element;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @UserController
 * @用户基本信息Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/user")
@Transactional
@CrossOrigin
public class UserController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private RedisClusterCache redisClusterCache;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserAuthMsgService userAuthMsgService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private CashRecordService cashRecordService;
    @Autowired
    private UserAccountService userAccountService;
    private final static Map keymap = new HashMap<String,Object>();
    /**
     * @添加用户基本信息
     * @param user
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addUser(@RequestBody User user){
        log.debug("添加用户基本信息");
        userService.insert(user);
        return JsonResp.ok(user);
    }

    /**
     * @修改用户基本信息
     * @param user
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateUser(@RequestBody User user){
        log.debug("修改用户基本信息");
        userService.updateById(user);
        return JsonResp.ok(user);
    }




    /**
     * @根据id查找用户基本信息
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectUser(Long id){
        log.debug("查找用户基本信息");
        User user = userService.selectById(id);
        return JsonResp.ok(user);
    }



    /***
     * 充值
     * */
    @RequestMapping(value = "/recharge",method = RequestMethod.POST)
    public JsonResp recharge(@RequestBody User user){
        Map map=adminService.findLoginUser();
            if (map.get("user")!=null && map.get("user")!=""){
                if (keymap.get("code")==null|| keymap.get("phone")==null ||!user.getCode().equals(keymap.get("code").toString()) ||!((Admin)map.get("user")).getPhone().equals(keymap.get("phone"))) {
                    return JsonResp.fa("验证码错误!");
                }
                User user1=userService.selectById(user);
                CashRecord cashRecord=new CashRecord();
                cashRecord.setUptDatetime(new Date());
                cashRecord.setGmtDatetime(new Date());
                cashRecord.setUserId(user.getId());
                cashRecord.setTransactionNum(OrderUtils.getOrderNo());
                cashRecord.setAdminid(((Admin)map.get("user")).getId());
                cashRecord.setRecoedType(1);
                cashRecord.setMoney(user.getTotalassets());
                cashRecord.setPayType(5);
                cashRecord.setStatus(1);
                Boolean boo=cashRecordService.insert(cashRecord);
                     if (boo==false){
                         return JsonResp.fa("充值失败");
                     }else{
                        user1.setTotalassets(user1.getTotalassets().add(user.getTotalassets()));
                        Boolean boso=userService.updateById(user1);
                         return JsonResp.ok();
                     }
             }else{
                return JsonResp.fa("后台未发现管理员信息");
            }
    }




    /**
     * @查找用户基本信息
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectPersonMsg", method = RequestMethod.GET)
    public JsonResp selectPersonMsg(){
        log.debug("查找用户基本信息");
        User loginUser=userService.findLoginUser();
        return JsonResp.ok(loginUser);
    }

    /**
     * @return 返回值JsonResp
     * @发送验证码
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.GET)
    public JsonResp sendCode(String phone)  {

        log.debug("发送验证码");
        if (!RegexUtils.isMobile(phone)){
            return JsonResp.fa("手机号格式不正确");
        }
/*        EntityWrapper<Tregister> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        Tregister findUser = tregisterService.selectOne(ew);*/
        String code = RandomUtils.randomString(4);
        /**是否已注册**/
/*        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        User oldUser = userService.selectOne(ew);
        if (oldUser != null) {
            return JsonResp.fa("该手机号已经注册");
        }*/
//        redisClusterCache.putCacheWithExpireTime(phone,code,5*60);
        InputStream result = smsService.smsCodeByType(phone, code);
//        MsgReturn msgReturn = (MsgReturn) JSONUtils.parse(resault);
        System.out.println("调用短信接口："+result);
        if (result!=null){
            try{
                Element stream = XmlUtils.getRootElementFromStream(result);
                String s = XmlUtils.getElementValue(stream);
                if (!(Long.parseLong(s)<0)){
                    redisClusterCache.putCacheWithExpireTime(phone,code,5*60);
                    return JsonResp.ok("短信发送成功");
                }
                log.debug("短信验证返回值："+s);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

//        String s = XmlUtils.getAttributeValue(rootElement,"string");


        return JsonResp.fa("短信发送失败");

    }





    /**
     * @return 返回值JsonResp
     * @发送验证码
     */
/*    @RequestMapping(value = "/adminsendCode", method = RequestMethod.GET)
    public JsonResp adminsendCode(Integer type) {
        log.debug("后台发送验证码");
        Map map=adminService.findLoginUser();

           if (map.get("user")!=null && map.get("user")!=""){
               SmsService.SmsTemplate.SmsContentCode smsContentCode = smsService.smsCodeByType(((Admin)map.get("user")).getPhone(), type);
               keymap.put("phone",((Admin)map.get("user")).getPhone());
               keymap.put("code",smsContentCode.getCode());
               return JsonResp.ok(smsContentCode);
           }else{
               return JsonResp.fa("未得到授权");
           }
    }*/


    /**
     * @param user
     * @return 返回值JsonResp
     * @注册
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JsonResp addMuser(@RequestBody User user) {
        log.debug("注册");
//        String code = request.getParameter("code");
        if (StringUtil.isEmpty(user.getCode())) {
            return JsonResp.fa("请输入验证码");
        }
        String cacheCode = redisClusterCache.getCache(user.getPhone());
        if (!user.getCode().equals(cacheCode)){
            return JsonResp.fa("验证码错误");
        }
        if(StringUtil.isEmpty(user.getPassword()))
            return JsonResp.toFail("密码不能为空");

        /*if (redisClusterCache.getCache(user.getPhone())==null||code==null) {
            return JsonResp.fa("验证码错误");
        }
        if (!code.equals(redisClusterCache.getCache(user.getPhone()))) {
            return JsonResp.fa("验证码错误");
        }*/

        /**是否已注册**/
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("phone", user.getPhone());
        User oldUser = userService.selectOne(ew);
        if (oldUser != null) {
            return JsonResp.fa("该手机号已经注册");
        }

        /**创建用户**/
        if (user.getReferralCode()!=null && org.apache.commons.lang3.StringUtils.isNotBlank(user.getReferralCode().toString())){
            EntityWrapper<User> entityWrapperDl = new EntityWrapper<>();
            entityWrapperDl.eq("codedl",user.getReferralCode());
            User userDl = userService.selectOne(entityWrapperDl);
            if (userDl==null){
                return JsonResp.fa("邀请码无效");
            }
            user.setChannelOneId(userDl.getId());
        }

        user.setPassword(Md5.md5Encode(user.getPassword()));
        user.setGmtDatetime(new Date());
        user.setAuthStatus(1);
        Integer codeDl = redisClusterCache.getCache("codedl");
        if (codeDl==null){
            redisClusterCache.putCache("codedl",1);
            codeDl =1;
        }else {
            codeDl++;

        }
        redisClusterCache.putCache("codedl",codeDl);
        String newCodeDl = StringUtils.leftPad(codeDl.toString(),8,"0");
        user.setCodedl(newCodeDl);
        boolean b = userService.insert(user);
        if (b){
            EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
            userEntityWrapper.eq("phone",user.getPhone());
            User user1 = userService.selectOne(userEntityWrapper);
            UserAccount userAccount = new UserAccount();
            userAccount.setUserId(user1.getId());
            userAccount.setMoney(0.0F);
            boolean b1 = userAccountService.insert(userAccount);
            if (b1){
                return JsonResp.ok(user);
            }
        }

        return JsonResp.fa("用户创建失败");
    }


    /**
     * @param phone    用户名
     * @param password 密码
     * @return 返回值JsonResp
     * @(前台)登录
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public JsonResp login(String phone, String password)  throws UnsupportedEncodingException {
        log.debug("(前台)登录");
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        ew.in("status", "1");//账号状态1代表正常2代表封号3异地系统注册
        User user = userService.selectOne(ew);
        if (user == null) {
            return JsonResp.fa("账号错误或者已被禁用！");
        }
        if (StringUtil.isEmpty(password) || !Md5.md5Encode(password).equals(user.getPassword())) {
            return JsonResp.fa("密码错误！");
        }

        return userService.loginByPhone(URLDecoder.decode(phone, "utf-8"), password);


    }

    /**
     * @param phone    用户名
     * @param newPassword 密码
     * @return 返回值JsonResp
     * @(前台)找回登录密码
     */
    @RequestMapping(value = "/getBackPassword", method = RequestMethod.GET)
    public JsonResp getBackPassword(String phone, String newPassword, String code){
        log.debug("找回登录密码");
        EntityWrapper<User> ew = new EntityWrapper<>();
        ew.eq("phone", phone);
        User user = userService.selectOne(ew);
        if(user==null){
            return JsonResp.fa("该手机号未注册");
        }
        if (StringUtil.isEmpty(code)) {
            return JsonResp.fa("请输入验证码");
        }
       /* if (redisClusterCache.getCache(loginUser.getPhone())==null||code==null) {
            return JsonResp.fa("验证码错误");
        }
        if (!code.equals(redisClusterCache.getCache(loginUser.getPhone()))) {
            return JsonResp.fa("验证码错误");
        }*/
        if(!code.equals(redisClusterCache.getCache(phone))){

            return JsonResp.fa("验证码错误");
        }
        user.setPassword(Md5.md5Encode(newPassword));
        user.setUptDatetime(new Date());
        userService.updateById(user);
        return JsonResp.ok();
    }

    /**
     * @param phone    用户名
     * @param newPassword 密码
     * @return 返回值JsonResp
     * @(前台)修改登录密码
     */
    @RequestMapping(value = "/changeLoginPassword", method = RequestMethod.GET)
    public JsonResp changeLoginPassword(String phone, String newPassword, String code){
        log.debug("修改登录密码");
        User loginUser=userService.findLoginUser();
        if(!(loginUser.getPhone().equals(phone))){
            return JsonResp.fa("该手机号未登录");
        }
        if (StringUtil.isEmpty(code)) {
            return JsonResp.fa("请输入验证码");
        }
       /* if (redisClusterCache.getCache(loginUser.getPhone())==null||code==null) {
            return JsonResp.fa("验证码错误");
        }
        if (!code.equals(redisClusterCache.getCache(loginUser.getPhone()))) {
            return JsonResp.fa("验证码错误");
        }*/

        loginUser.setPassword(Md5.md5Encode(newPassword));
        loginUser.setUptDatetime(new Date());
        userService.updateById(loginUser);
        return JsonResp.ok();
    }
    /**
     * @param oldPhone    用户名
     * @param code 验证码
     * @return 返回值JsonResp
     * @(前台)修改手机号第一步--旧手机验证
     */
    @RequestMapping(value = "/changePhoneOld", method = RequestMethod.GET)
    public JsonResp changePhoneOld(String oldPhone, String code){
        log.debug("修改手机号第一步");
        User loginUser=userService.findLoginUser();
        if(!(loginUser.getPhone().equals(oldPhone))){
            return JsonResp.fa("手机号错误");
        }
        if (StringUtil.isEmpty(code)) {
            return JsonResp.fa("请输入验证码");
        }
        /*if (redisClusterCache.getCache(oldPhone)==null||code==null) {
            return JsonResp.fa("验证码错误");
        }
        if (!code.equals(redisClusterCache.getCache(oldPhone))) {
            return JsonResp.fa("验证码错误");
        }*/
        return JsonResp.ok();
    }

    /**
     * @param newPhone    用户名
     * @param code 验证码
     * @return 返回值JsonResp
     * @(前台)修改登录手机第二步--新手机验证
     */
    @RequestMapping(value = "/changePhoneNew", method = RequestMethod.GET)
    public JsonResp changePhoneNew(String newPhone, String code){
        log.debug("修改登录手机第二步");
        User loginUser=userService.findLoginUser();
        if (StringUtil.isEmpty(code)) {
            return JsonResp.fa("请输入验证码");
        }
        /*if (redisClusterCache.getCache(newPhone)==null||code==null) {
            return JsonResp.fa("验证码错误");
        }
        if (!code.equals(redisClusterCache.getCache(newPhone))) {
            return JsonResp.fa("验证码错误");
        }*/
        loginUser.setPhone(newPhone);
        loginUser.setUptDatetime(new Date());
        userService.updateById(loginUser);
        return JsonResp.ok();
    }

    /**
     * @param
     * @return 返回值JsonResp
     * @(前台)校验支付密码
     */
    @RequestMapping(value = "/checkPayPassword", method = RequestMethod.GET)
    public JsonResp checkPayPassword(String payPassword){
        log.debug("校验支付密码");
        User loginUser=userService.findLoginUser();
        String s = Md5.md5Encode(loginUser.getPayPwd());
        System.out.println(s);
        if(Md5.md5Encode(payPassword).equals(loginUser.getPayPwd())){
            return JsonResp.ok("密码正确");
        }
        return JsonResp.fa("密码错误");
    }



    /**
     * @param phone    用户名
     * @param Password 密码
     * @return 返回值JsonResp
     * @(前台)设置或修改支付密码
     */
    @RequestMapping(value = "/changePayPassword", method = RequestMethod.GET)
    public JsonResp changePayPassword(String phone, String Password, String code){
        log.debug("设置或修改支付密码");
        User loginUser=userService.findLoginUser();
        if(Password==null){
            return JsonResp.fa("密码为空");
        }
        if(!(loginUser.getPhone().equals(phone))){
            return JsonResp.fa("手机号错误");
        }
        if (StringUtil.isEmpty(code)) {
            return JsonResp.fa("请输入验证码");
        }
       /* if (redisClusterCache.getCache(phone)==null||code==null) {
            return JsonResp.fa("验证码错误");
        }
        if (!code.equals(redisClusterCache.getCache(phone))) {
            return JsonResp.fa("验证码错误");
        }*/

        loginUser.setPayPwd(Md5.md5Encode(Password));
        loginUser.setUptDatetime(new Date());
        userService.updateById(loginUser);
        return JsonResp.ok();
    }

    /**
     * @备注：设置支付密码
     * @param payPassword
     * @return
     */
    @RequestMapping(value = "setPayPassword",method = RequestMethod.GET)
    public JsonResp setPayPassword(String payPassword){
        if (RegexUtils.isZipCode(payPassword)){
            User loginUser = userService.findLoginUser();
            redisClusterCache.putCacheWithExpireTime(loginUser.getPhone()+"pay",payPassword,10*60);
            return JsonResp.ok("支付密码获取成功");
        }
        return JsonResp.ok("支付密码不合法");
    }

    /**
     * @备注:确认支付密码
     * @param payPassword
     * @return
     */
    @RequestMapping("/confirmPayPassword")
    public JsonResp confirmPayPassword(String payPassword){
        User loginUser = userService.findLoginUser();
        String firstPayPassword = redisClusterCache.getCache(loginUser.getPhone()+"pay");
        if (RegexUtils.isZipCode(payPassword)&&payPassword.equals(firstPayPassword)){
            EntityWrapper<User> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("id",loginUser.getId());

            loginUser.setPayPwd(Md5.md5Encode(payPassword));
            boolean b = userService.update(loginUser, entityWrapper);
            if (b){

                return JsonResp.ok("支付密码设置成功");

            }
        }
        return JsonResp.fa("两次密码不一致或第一次密码已失效");
    }
    /*
    *添加银行卡
     */
 /*   @RequestMapping(value = "/addbankcard",method = RequestMethod.GET)
    public JsonResp addBankCard(String realName,String idCard,String phone,String bankNum){
        BankCard bankCard = new BankCard();

        return JsonResp.ok("添加成功");
    }*/
    /***
     * 实名认证
     * */
    @RequestMapping(value = "/authentication",method = RequestMethod.POST)
    public JsonResp authentication(@RequestBody UserAuthMsg userAuthMsg){
        User user=userService.findLoginUser();
        EntityWrapper entityWrapper=new EntityWrapper();
        entityWrapper.eq("user_id",1);
        UserAuthMsg userAuthMsg1= userAuthMsgService.selectOne(entityWrapper);

                    if (userAuthMsg1==null){
                        Map<String,String> params = new HashMap<>();
                        params.put("name",userAuthMsg.getRealName());
                        params.put("idcard",userAuthMsg.getIdCard());
                        params.put("acc_no",userAuthMsg.getBankNum());
                        params.put("mobile",user.getPhone());
                        CheckBankCard checkBankCard = new CheckBankCard();
                        String s = checkBankCard.CheckBankNum(params);
                        System.out.println(s);
                       /* userAuthMsg.setUserId(user.getId());
                        Boolean boo= userAuthMsgService.insert(userAuthMsg);*/
                        return JsonResp.ok(true);
                    }else{
                        return JsonResp.fa("返回");
                    }

    }




    /**
     * @注销
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public JsonResp logout() {
        log.debug("注销");
        userService.logout();
        return JsonResp.ok();
    }


       /***
        * 后台管理所有用户
        * */
     @RequestMapping(value ="/selectUserlist",method = RequestMethod.GET)
     public JsonResp  selectUserlist(Page page,User user){
         Channel channel=null;
         Map map=new HashMap();
         map.put("user",user);
         map.put("pageNo",(page.getCurrent()-1)*page.getSize());
         map.put("pageSize",page.getSize());
         List<User> userList=userService.selectUserlist(map);
         Integer sun=userService.selectUserlistsun(map);
              if (userList!=null){
                    for (User us:userList){
                             if (us.getAuthStatus()==1){
                                 EntityWrapper entityWrapper=new EntityWrapper();
                                 entityWrapper.eq("user_id",us.getId());
                                 UserAuthMsg userAuthMsg=userAuthMsgService.selectOne(entityWrapper);
                                 if (userAuthMsg!=null){
                                     us.setUserAuthMsg(userAuthMsg);
                                 }
                             }
                          if (us.getChannelOneId()!=null){
                                if(us.getChannelTwoId()==null){
                           us.setChannel(channelService.selectById(us.getChannelOneId()));

                                }
                              if(us.getChannelTwoId()!=null){
                                    if (us.getChannelThreeId()!=null){
                              us.setChannel(channelService.selectById(us.getChannelThreeId()));

                                    }
                                  if (us.getChannelThreeId()==null){
                              us.setChannel(channelService.selectById(us.getChannelTwoId()));

                                  }
                              }
                          }
                    }
              }
         return JsonResp.ok(new PageDto(page.getCurrent(),page.getSize(),userList,sun));
     }



     /***
      * 根据代理商id查询用户
      * */
    @RequestMapping(value ="/selectChannter",method = RequestMethod.GET)
    public  JsonResp selectChannter(Long chanId){
       Channel channel=channelService.selectById(chanId);
        EntityWrapper entityWra=new EntityWrapper();
        entityWra.eq("status",1);
          if (channel.getLevel()==1){
              entityWra.eq("channel_one_id",chanId);
          }else if(channel.getLevel()==2){
              entityWra.eq("channel_two_id",chanId);
          }else if (channel.getLevel()==3){
              entityWra.eq("channel_three_id",chanId);
          }
        List<User> userList=userService.selectList(entityWra);
            if (!userList.isEmpty()){
                for(User us:userList){
                    if (us.getChannelThreeId()==null){
                             if (us.getChannelTwoId()==null){
                                   if (us.getChannelOneId()==null){
                                   }else{
                                       EntityWrapper entity2=new EntityWrapper();
                                       entity2.eq("id",us.getChannelOneId());
                                       Channel channel1=channelService.selectOne(entity2);
                                       us.setChannel(channel1);
                                   }
                             }else{
                                 EntityWrapper entity2=new EntityWrapper();
                                 entity2.eq("id",us.getChannelTwoId());
                                 Channel channel1=channelService.selectOne(entity2);
                                 us.setChannel(channel1);
                             }
                    }else{
                        EntityWrapper entity2=new EntityWrapper();
                        entity2.eq("id",us.getChannelThreeId());
                       Channel channel1=channelService.selectOne(entity2);
                       us.setChannel(channel1);
                    }
                }
            }
        return JsonResp.ok(userList);
    }


}
